import 'package:flutter/material.dart';
import 'dart:isolate';
import 'dart:convert';
import 'package:http/http.dart' as http;

///Isolate开启新的线程进行耗时操作并返回数据更新UI的方法
class IsolatePage extends StatefulWidget {
  @override
  _IsolatePageState createState() => _IsolatePageState();
}

class _IsolatePageState extends State<IsolatePage> {
  List _widgets = [];

  loadData() async {
    //打开ReceivePort接收数据
    ReceivePort receivePort = ReceivePort();

    //创建并生成与当前Isolate共享数据的Isolate
    await Isolate.spawn(dataLoader, receivePort.sendPort);

    //流的第一个元素
    SendPort sendPort = await receivePort.first;
    //流的第一个元素被接收到后会关闭，需要新创建一个ReceivePort来接收消息
    ReceivePort response = ReceivePort();
    //通过发送窗口向对应的receivePort发送消息（也就是下面send的数组参数）
    sendPort
        .send(['http://jsonplaceholder.typicode.com/posts', response.sendPort]);

    //获取端口发送来的数据
    List msg = await response.first;

    setState(() {
      _widgets = msg;
    });
  }

  ///isolate的入口函数，在新的Isolate中调用，Isolate.spawn中的message作为唯一的参数
  static dataLoader(SendPort sendPort) async {
    //打开ReceivePort来接收传入的消息
    ReceivePort receivePort = ReceivePort();
    //通知其它Isolate，本Isolate所监听的端口
    sendPort.send(receivePort.sendPort);
    //获取其它端口发送的消息msg-->["http://jsonplaceholder.typicode.com/posts", response.sendPort]
    await for (var msg in receivePort) {
      //相当于List msg=await receivePort.first
      String data = msg[0];
      SendPort replyTo = msg[1];

      String dataURL = data;
      http.Response response = await http.get(dataURL);
      if(response.statusCode==200){
        //向对应的ReceivePort发送json解析的数据
        replyTo.send(json.decode(response.body));
      }else{
        print('后台接口出错');
      }
    }
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: getBody(),
        ),
      ),
    );
  }

  Widget getBody() {
    if (_widgets.length == 0) {
      return SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text('通过Isolate开启新线程请求数据中...'),
            CircularProgressIndicator(),
          ],
        ),
      );
    } else {
      return ListView.builder(
        itemCount: _widgets.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_widgets[index]['title']),
          );
        },
      );
    }
  }
}
